package org.hjq.service.impl;

import org.hjq.entity.LdapUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Service;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;

import static org.springframework.ldap.query.LdapQueryBuilder.query;

@Service
public class LDAPService {

    @Autowired
    private LdapTemplate ldapTemplate;

    // 添加对象方法
    public String addInfoToLDAP(LdapUser ldapUser) {
//        ldapTemplate.bind(ldapUser.getDn(), null, getAttributes(ldapUser));
        ldapTemplate.create(ldapUser);
        return "ok";
    }

    public LdapUser findByCn(String cn) {
        ldapTemplate
                .search(query().where("objectClass").is("inetOrgPerson"),new AttributesMapper() {
            @Override
            public LdapUser mapFromAttributes(Attributes attributes) throws NamingException, javax.naming.NamingException {
                //If you don’t know what attributes are in ldap, you can print them in the following way
                // NamingEnumeration<? extends Attribute> att = attr.getAll();
                //while (att.hasMore()) {
                //  Attribute a = att.next();
                // System.out.println(a.getID());
                //}
                LdapUser p = new LdapUser();

                Attribute a = attributes.get("cn");
                if (a != null) p.setCn((String) a.get());

                a = attributes.get("uid");
                if (a != null) p.setUserId((String) a.get());

                a = attributes.get("sn");
                if (a != null) p.setSn((String) a.get());

                a = attributes.get("userPassword");
                if (a != null) p.setPublicKey(a.get().toString());
                return p;
            }
        }).forEach(System.out::println);
        return ldapTemplate.findOne(query().where("cn").is(cn),LdapUser.class);
    }
    public Boolean valid(String cn) {
        ldapTemplate.authenticate(query().where("cn").is(cn),"123456");
        return true;
    }

    public LdapUser update(LdapUser ldapUser) {
        ldapTemplate.update(ldapUser);
        return ldapUser;
    }

    public LdapUser delete(LdapUser ldapUser) {
        ldapTemplate.delete(ldapUser);
        return ldapUser;
    }

    private Attributes getAttributes(LdapUser ldapUser) {
        BasicAttributes attributes = new BasicAttributes();
        attributes.put("objectClass", "top");
        attributes.put("objectClass", "LdapUser");
        attributes.put("cn", ldapUser.getCn());
        attributes.put("userId", ldapUser.getUserId());
        attributes.put("publicKey", ldapUser.getPublicKey());
        return attributes;
    }

}
